var router = require('express').Router();
var util = require('util');
var EventProxy = require("eventproxy");
var async = require("async");

var Consts = require('../consts');
var resultJson = require('../result-json');
var Utils = require('../utils');
var logger = require('../models/logger');
var ErrSet = require('../models/ErrSet');
var User = require('../models/User');

router.post('/', function(req, res) {
	res.send('respond with a resource');
});

//查询某用户某课程下的错题集
router.post('/list', function(req, res) {
	var errset = req.body;
	var proxy = new EventProxy();
	proxy.all("results", "count", function(results, count) {
		res.send(resultJson(0, {
			results: results,
			count: count
		}))
	})
	var start = errset.start || 0;
	var count = errset.count || Consts.MAX;
	var item = {
		owner: errset.owner || req.body._user._id
	}
	if (errset.cid || errset.cid != "")
		item = {
			owner: errset.owner || req.body._user._id,
			cid: errset.cid
		}

	ErrSet.find(item).skip(start).limit(count).sort({
		create: -1
	}).exec(function(err, errsets) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		proxy.emit("results", errsets);
	});

	ErrSet.find(item).count(function(err, num) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		proxy.emit("count", num);
	});
});

//批量添加错题集
router.post('/add', function(req, res) {
	var errset = req.body.errset; //  []
	if (typeof errset == "string") {
		errset = [errset];
	}
	async.each(errset, function(item, cb) {
		item.create = new Date();
		item.owner = req.body._user._id;
		new ErrSet(item).save(function(err) {
			if (err)
				cb(err);
			cb();
		});
	}, function(err) {
		if (err) {
			logger.error(err);
			return res.send(resultJson(2));
		}
		res.send(resultJson(0));
	});
});

//删除错题集
router.post('/remove', function(req, res) {
	var errset = req.body;
	ErrSet.remove({
		_id: errset._id
	}, function(err) {
		if (err) {
			logger.error(err);
			res.send(resultJson(2));
		} else
			res.send(resultJson(0));
	})
});
module.exports = router;